package pl.cat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.provider.OpenableColumns;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class HttpRequest implements Runnable {
	private static final String SOURCE = "http://dl.dropboxusercontent.com/u/8086560/JUG%20Hackaton/JugEvents.json";
	private static final String SOURCE_TEXT = "http://dl.dropboxusercontent.com/u/8086560/JUG%20Hackaton/text.json";
	private static final String TAG = "HttpRequest";
	private static final String JUG_FILE = "jugFile";
	private static final String TEXT_FILE = "textFile";
	
	private LiveWallpaperService lws;
	
	private Context context;
	
	public HttpRequest(Context c) {
		context = c;
		lws = null;
	}
	
	public HttpRequest(Context c, LiveWallpaperService l) {
		context = c;
		lws = l;
	}

	public String downloadEvents(String url) {

		StringBuffer sBuf = new StringBuffer();

		try {
			URL u = new URL(url);

			URLConnection uc = u.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					uc.getInputStream()));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				sBuf.append(inputLine);
			}
			in.close();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}

		// [{"id":1,"start":"2013 09 30, 18.00",
		// "topic":"abc","description":"blaaa"}]
		Log.d(TAG, "json: "+sBuf.toString());
		return sBuf.toString();
	}

	private void parseToJSON(String data, String fileName) {
		List<JugEvent> events = new ArrayList<JugEvent>();

		Gson gson = new Gson();
		
		JsonParser parser = new JsonParser();
		JsonArray jarray;
		try {
			jarray = parser.parse(data).getAsJsonArray();
		} catch (IllegalStateException ise)	{
			return;
		}

	    for(JsonElement obj : jarray )
	    {
	    	JugEvent je = gson.fromJson(obj, JugEvent.class);
	    	events.add(je);
	    }
		
		Log.d(TAG, "LISTA: ");
		Log.d(TAG, events.toString());
		
		FileOutputStream outputStream;
		File file = new File(context.getFilesDir(), fileName);
		try {
		  outputStream = new FileOutputStream(file);
		  ObjectOutputStream oout = new ObjectOutputStream(outputStream);
		  oout.writeObject(events);
		  oout.close();
		} catch (Exception e) {
		  e.printStackTrace();
		}
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		String data = downloadEvents(SOURCE);
		if (data!=null)
		{
			parseToJSON(data, JUG_FILE);
			if (lws!=null)
			{
				DataClient dc = new DataClient(context);
				lws.setEvents(dc.readFile(JUG_FILE));
			}
		}
		
		
		String text = downloadEvents(SOURCE_TEXT);
		if (text!=null)
		{
			parseToJSON(text, TEXT_FILE);
			if (lws!=null)
			{
				DataClient dc = new DataClient(context);
				lws.setTexts(dc.readFile(TEXT_FILE));
			}
		}
	}

}
